/**
 * Created by Administrator on 2017/9/13.
 */
let msg = require('../util/msg.js');
let mem = require('../util/mem.js');
let util = require('../util/util.js');
let mailUtil = require('../util/mailUtil.js');
let log = require('../util/log.js');
let gameData = require('../util/gameData.js');
let chipDao = require('../mysql/chipDao.js');

let method = module.exports;

method.chipId = 300001;
method.pool = 1000;
method.nextTime = 0;
method.job = null;
method.getPlayer = function (userId, key) {
    if (!mem.slotMachinePlayers[userId]) {
        return null;
    }
    return mem.slotMachinePlayers[userId][key];
};
method.setPlayer = function (userId, key, value) {
    if (!mem.slotMachinePlayers[userId]) {
        return false;
    }
    mem.slotMachinePlayers[userId][key] = value;
};
method.addPlayer = function (userId, key, value) {
    if (!mem.slotMachinePlayers[userId]) {
        return false;
    }
    mem.slotMachinePlayers[userId][key] += value;
};
method.getRank = function (userId, key) {
    if (!mem.slotMachineRanks[userId]) {
        return null;
    }
    return mem.slotMachineRanks[userId][key];
};
method.setRank = function (userId, key, value) {
    if (!mem.slotMachineRanks[userId]) {
        return false;
    }
    mem.slotMachineRanks[userId][key] = value;
};
method.addRank = function (userId, key, value) {
    if (!mem.slotMachineRanks[userId]) {
        return false;
    }
    mem.slotMachineRanks[userId][key] += value;
};
method.join = function (userId, cid, uuid, data) {
    if (mem.slotMachinePlayers[userId]) {
        return false;
    }
    mem.slotMachinePlayers[userId] = {};
    method.setPlayer(userId, 'uuid', uuid);
    method.setPlayer(userId, 'cid', cid);
    method.setPlayer(userId, 'gold', data.gold);
    method.setPlayer(userId, 'chip', data.chip);
    method.setPlayer(userId, 'bonus', 0);

    let resultData = {};
    if (!mem.slotMachineRanks[userId]) {
        mem.slotMachineRanks[userId] = {};
        method.setRank(userId, 'userId', userId);
        method.setRank(userId, 'name', data.name);
        method.setRank(userId, 'avatar', data.avatar);
        method.setRank(userId, 'bonus', 0);
        resultData.user = {'userId': userId, 'name': data.name, 'avatar': data.avatar, 'bonus': 0};
    }

    let restTime = Math.floor((method.nextTime - Date.now()) / 1000);
    let user = [];
    for (let key in mem.slotMachineRanks) {
        user.push(mem.slotMachineRanks[key]);
    }
    msg.send(cid, uuid, 'activitySlotMachineJoin', {
        'user': user,
        'pool': method.pool,
        'restTime': restTime
    });

    method.msg(resultData);
};
method.play = function (userId, cid, uuid, data) {
    if (!mem.slotMachinePlayers[userId]) {
        return false;
    }
    if (method.getPlayer(userId, 'bonus') > 0) {
        method.return(userId, cid, uuid, data);
        return false;
    }
    let useChip = 0;
    let winChip = 0;
    for (let i in data) {
        useChip += data[i] * 1;
    }
    if (useChip > method.getPlayer(userId, 'chip')) {
        msg.send(cid, uuid, 'error', {'api': 'activitySlotMachinePlay', 'code': 10075});
        return false;
    }
    let resultData = {};

    delete mem.slotMachinePlayers[userId].double;
    method.addPlayer(userId, 'chip', -useChip);
    method.deduct(userId, cid, uuid, useChip);

    let table = {};
    for (let i in gameData.d.slotMachine) {
        table[i] = gameData.d.slotMachine[i].random;
    }
    let keys = [];
    let index = 1;
    while (true) {
        let pointer = index;
        index = 0;
        let roundKeys = [];
        for (let j = 0; j < pointer; j++) {
            let key = parseInt(util.roundTable(table));
            if (isNaN(key)) {
                break;
            }
            let sm = gameData.d.slotMachine[key];
            if (sm.type == 0) {
                index += sm.rate;
            }
            if (data[sm.type]) {
                method.addPlayer(userId, 'bonus', (data[sm.type] * 1 * sm.rate));
                winChip += (data[sm.type] * 1 * sm.rate);
                useChip -= (data[sm.type] * 1);
            }
            delete table[key];
            roundKeys.push(key);
        }
        if (roundKeys.length > 0) {
            keys.push(roundKeys);
        }
        if (index == 0) {
            break;
        }
    }
    // 赢的进排行
    method.addRank(userId, 'bonus', winChip);
    // 输的进奖池
    method.pool += (useChip * gameData.d.config.slotMachinePoolRate * gameData.d.chip[method.chipId].goldSell);

    resultData.rank = {'userId': userId, 'bonus': method.getPlayer(userId, 'bonus')};
    resultData.pool = Math.floor(method.pool);
    if (winChip >= gameData.d.config.slotMachineMarqueeBonus) {
        resultData.play = {'userId': userId, 'bonus': winChip};
    }

    msg.send(cid, uuid, 'activitySlotMachinePlay', {
        'keys': keys,
        'chip': method.getPlayer(userId, 'chip'),
        'bonus': method.getPlayer(userId, 'bonus')
    });

    method.msg(resultData);
};
method.double = function (userId, cid, uuid, data) {
    if (!mem.slotMachinePlayers[userId]) {
        return false;
    }
    if (method.getPlayer(userId, 'bonus') <= 0) {
        msg.send(cid, uuid, 'error', {'api': 'activitySlotMachineDouble', 'code': 10076});
        return false;
    }
    if (method.getPlayer(userId, 'chip') < method.getPlayer(userId, 'bonus')) {
        msg.send(cid, uuid, 'error', {'api': 'activitySlotMachineDouble', 'code': 10080});
        return false;
    }
    if (method.getPlayer(userId, 'double')) {
        msg.send(cid, uuid, 'error', {'api': 'activitySlotMachineDouble', 'code': 10081});
        return false;
    }

    let bonus = method.getPlayer(userId, 'bonus');
    method.setPlayer(userId, 'double', true);
    method.addPlayer(userId, 'chip', -bonus);
    method.addPlayer(userId, 'bonus', bonus);
    method.deduct(userId, cid, uuid, bonus);

    msg.send(cid, uuid, 'activitySlotMachineDouble', {
        'chip': method.getPlayer(userId, 'chip'),
        'bonus': method.getPlayer(userId, 'bonus')
    });
};
method.deduct = function (userId, cid, uuid, chip) {
    let chipModel = new chipDao();
    chipModel.inChipId(userId, method.chipId, function (err, res) {
        let resultData2 = {};
        chipModel.addNum(-chip);
        resultData2[method.chipId] = {'now': chipModel.data.num, 'add': -chip};
        chipModel.save(function (err3, res3) {
            msg.send(cid, uuid, 'globalChipChange', resultData2);
        });
    });
};
method.dice = function (userId, cid, uuid, data) {
    if (!mem.slotMachinePlayers[userId]) {
        return false;
    }
    if (method.getPlayer(userId, 'bonus') <= 0) {
        msg.send(cid, uuid, 'error', {'api': 'activitySlotMachineDice', 'code': 10076});
        return false;
    }
    let resultData = {};
    let randValue = util.random(1, 14);
    let randResult = 'a';
    if (randValue >= 8) {
        randResult = 'b';
    }
    if (data.key == randResult) {
        method.setRank(userId,'bonus',method.getPlayer(userId, 'bonus'));
        method.addPlayer(userId,'bonus',method.getPlayer(userId, 'bonus'));
        resultData.rank = {'userId': userId, 'bonus':method.getRank(userId,'bonus')};
        if (method.getPlayer(userId, 'bonus') >= gameData.d.config.slotMachineMarqueeBonus) {
            resultData.play = {'userId': userId, 'bonus': method.getPlayer(userId, 'bonus')};
        }
    } else {
        method.pool += (method.getPlayer(userId, 'bonus') * gameData.d.config.slotMachinePoolRate * gameData.d.chip[method.chipId].goldSell);
        method.setPlayer(userId,'bonus',0);
        resultData.pool = Math.floor(method.pool);
    }
    msg.send(cid, uuid, 'activitySlotMachineDice', {
        'value': randValue,
        'bonus': method.getPlayer(userId, 'bonus')
    });

    method.msg(resultData);
};
method.return = function (userId, cid, uuid, data) {
    if (!mem.slotMachinePlayers[userId]) {
        return false;
    }
    if (method.getPlayer(userId, 'bonus') <= 0) {
        msg.send(cid, uuid, 'error', {'api': 'activitySlotMachineDouble', 'code': 10076});
        return false;
    }
    method.back(userId, cid, uuid, function () {
        msg.send(cid, uuid, 'activitySlotMachineReturn');
    });
};
method.exit = function (userId, cid, uuid, data) {
    if (!mem.slotMachinePlayers[userId]) {
        return false;
    }
    method.back(userId, cid, uuid, function () {
        delete mem.slotMachinePlayers[userId];
        msg.send(cid, uuid, 'activitySlotMachineExit');
    });
};
method.back = function (userId, cid, uuid, cb) {
    let chipModel = new chipDao();
    chipModel.inChipId(userId, method.chipId, function (err, res) {
        let resultData2 = {};
        chipModel.addNum(method.getPlayer(userId, 'bonus'));
        resultData2[method.chipId] = {'now': chipModel.data.num, 'add': method.getPlayer(userId, 'bonus')};
        chipModel.save(function (err3, res3) {
            msg.send(cid, uuid, 'globalChipChange', resultData2);
            method.setPlayer(userId,'chip',chipModel.data.num);
            method.setPlayer(userId,'bonus',0);
            cb();
        });
    });
};
method.settlement = function () {
    let ranks = {};
    let pool = method.pool;
    for (let i in mem.slotMachineRanks) {
        if (method.getRank(i,'bonus') > 0) {
            ranks[i] = mem.slotMachineRanks[i];
        }
        if (mem.slotMachinePlayers[i]) {
            method.setRank(i,'bonus',0);
        } else {
            delete mem.slotMachineRanks[i];
        }
    }
    method.pool = 1000;

    // 如果没有参与者则不进行发奖
    let rankKeys = Object.keys(ranks);
    if (rankKeys.length <= 0) {
        return false;
    }
    let keys = rankKeys.sort(function (a, b) {
        return ranks[b].bonus - ranks[a].bonus;
    });
    let list = {};
    let bonus = 0, tempNum = 0, finalNum = 0;
    let rankLength = Object.keys(gameData.d.slotMachineRank).length;
    for (let i in keys) {
        tempNum++;
        if (bonus != ranks[keys[i]].bonus) {
            finalNum = tempNum;
        }
        bonus = ranks[keys[i]].bonus;
        if (!list[finalNum]) {
            list[finalNum] = [];
        }
        list[finalNum].push(keys[i]);
        if (finalNum >= (rankLength - 1)) {
            break;
        }
    }
    //let rewardRate = [0.5, 0.15, 0.1, 0.1, 0.1, 0.05, 0.05, 0.05, 0.05, 0.05];
    for (let i in list) {
        if (i >= (rankLength - 1)) {
            break;
        }
        let r = parseInt(i) + 1;
        let reward = pool * ((gameData.d.slotMachineRank[r].bonusRatio / 100) / list[i].length);
        for (let j in list[i]) {
            let attachment = {};
            attachment.gold = Math.floor(reward);
            mailUtil.send(0, list[i][j], '系统', '', '魔盒第' + r + '名奖励', attachment);
        }
    }
    let resultData = {};
    resultData.settlement = true;
    resultData.pool = method.pool;
    resultData.restTime = Math.floor((method.nextTime - Date.now()) / 1000);
    method.msg(resultData);
};
method.setNextTime = function (nextTime) {
    method.nextTime = nextTime;
};
method.msg = function (resultData) {
    method.broadcast('activitySlotMachineBroadcast', resultData);
};
method.broadcast = function (action, obj) {
    for (let i in mem.slotMachinePlayers) {
        let player = mem.slotMachinePlayers[i];
        if (obj) {
            msg.send(player.cid, player.uuid, action, obj);
        } else {
            msg.send(player.cid, player.uuid, action);
        }
    }
};
